import os
import re
from syntax_check import check_syntax as php_check_syntax
from bs4 import BeautifulSoup
import esprima


def check_html_syntax(html_file_path):
    try:
        with open(html_file_path, 'r', encoding='utf-8') as f:
            html_content = f.read()

        soup = BeautifulSoup(html_content, 'html.parser')
        errors = []

        for error in soup.decode_contents(formatter="html").splitlines():
            if "Error" in error:
                errors.append(error)

        if errors:
            print(f"HTML文件 {html_file_path} 存在以下语法错误：")
            for error in errors:
                print(f"    - {error}")
    except Exception as e:
        print(f"检查HTML文件 {html_file_path} 时出错：{e}")


def check_js_syntax(js_file_path):
    try:
        with open(js_file_path, 'r', encoding='utf-8') as f:
            js_content = f.read()

        try:
            esprima.parseScript(js_content)
        except esprima.Error as e:
            print(f"JS文件 {js_file_path} 存在以下语法错误：")
            print(f"    - {e.description}")
    except Exception as e:
        print(f"检查JS文件 {html_file_path} 时出错：{e}")


def check_php_syntax(php_file_path):
    try:
        php_check_syntax(php_file_path)
    except SyntaxError as e:
        print(f"PHP文件 {php_file_path} 存在以下语法错误：")
        print(f"    - {e}")
    except Exception as e:
        print(f"检查PHP文件 {php_file_path} 时出错：{e}")


def scan_project_files(project_path):
    for root, dirs, files in os.walk(project_path):
        for file in files:
            file_path = os.path.join(root, file)
            if file.endswith(".html"):
                check_html_syntax(file_path)
            elif file.endswith(".js"):
                check_js_syntax(file_path)
            elif file.endswith(".php"):
                check_php_syntax(file_path)


if __name__ == "__main__":
    project_path = "E:/xufei/translate-erp/application"
    scan_project_files(project_path)